package com.atww.book.controller;

import com.atww.book.service.BookService;
import com.atww.book.entity.Book;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 汪汪
 * @version 1.0
 * @data 2024/1/6 10:41
 * @bug退散
 */
@Controller
public class BookController {
    @Autowired
    private BookService bookService;
    @Value("${book.path}")
    private String imgPath;

    @RequestMapping("/getPage")
    public String getPage(Model model, @RequestParam(defaultValue = "1") Integer pageNum, Book book){
       PageInfo<Book> page= bookService.getPage(pageNum,book);
       model.addAttribute("page",page);
       if (book!=null && book.getName()!=null){
           model.addAttribute("name",book.getName());
       }
        if (book!=null && book.getPrice()!=null){
            model.addAttribute("price",book.getPrice());
        }

       return "index";
    }
    @RequestMapping("/addBook")
    public String addBook(MultipartFile file,Book book,Model model){
        if (file==null || file.isEmpty()){
            model.addAttribute("error","图片不能为空!");
            return "add";
        }
        String fileName = file.getOriginalFilename();
        String substring=null;
        if (fileName != null) {
           substring = fileName.substring(fileName.lastIndexOf("."));
        }
        assert  substring!=null;
        if (!(substring.equalsIgnoreCase(".jpg")||
            substring.equalsIgnoreCase(".png"))){
            model.addAttribute("error","请选择格式为jpg,png的图片");
            return "add";
        }
        File uploadPath=new File(imgPath);
        if (!uploadPath.exists()){
            uploadPath.mkdirs();
        }
        String path=imgPath+"\\"+UUID.randomUUID().toString().replace("-","")+substring;
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        book.setImgurl(path);
        bookService.addBook(book);
        return "index";
    }
    @PostMapping("/delMany")
    public String delMany(String[] ids){
       bookService.delMany(ids);
        return "index";
    }
}
